var db = openDatabaseSync("MeeWords", "1.0", "Database of words", 1000000);


function openFile(file) {
    var component = Qt.createComponent(file)
    if (component.status == Component.Ready)
        pageStack.push(component);
    else
        console.log("Error loading component:", component.errorString());
}

function getDatabase() {
    return db
}

/*******************************************************************/

var bufWordsLearn = new Array()
var bufCateroiesLearn = new Array()

function clearCategoryLearn() {
    bufCateroiesLearn = [ ]
}

/* добавление id категории к списку, по которым будет проводится изучение слов */
function addCategoryLearn( cat_id ) {
    bufCateroiesLearn[ bufCateroiesLearn.length ] = cat_id
    //console.log( bufCateroiesLearn.length + "=>" +  bufCateroiesLearn[ bufCateroiesLearn.length-1 ] )
}

/* */
function getAllWordsLearn( direct ) {
    bufWordsLearn = new Array() //очистка массива

    db.transaction ( function(tx) {
                       var sql = "SELECT id, word, translation, show_true, show_false FROM words WHERE "
                       for(var s=0; s<bufCateroiesLearn.length; s++) {
                           if ( s == 0 ) {
                               sql += " category_id = " + bufCateroiesLearn[s]
                           } else {
                               sql += " OR category_id = " + bufCateroiesLearn[s]
                           }
                       }
                       var res = tx.executeSql( sql )
                       for( var i = 0; i<=res.rows.length-1; i++ ) {
                           var nameWord = res.rows.item(i).word;
                           var transWord = res.rows.item(i).translation;
                           var idWord = res.rows.item(i).id;
                           var trueWord = res.rows.item(i).show_true;
                           var falseWord = res.rows.item(i).show_false;

                           var buf = new Object()
                           if ( direct === 0 ) {
                               buf.word = nameWord
                               buf.translation = transWord
                               buf.id = idWord
                               buf.strue = trueWord
                               buf.sfalse = falseWord
                               bufWordsLearn[ i ] = buf
                           } else {
                               buf.word = transWord
                               buf.translation = nameWord
                               buf.id = idWord
                               buf.strue = trueWord
                               buf.sfalse = falseWord
                               bufWordsLearn[ i ] = buf
                           }
                       }
                   }
                )
    return bufWordsLearn
}

function getNumWordsLearn() {
    return bufWordsLearn.length
}

/* */
function getWord( buff ) {
    var lenBuf = buff.length
    if ( lenBuf === 0) {
        return undefined
    }

    var num = Math.floor( lenBuf*Math.random() )
    num = num % lenBuf
    //console.log("nextWord(): num="+num + " lenBuf="+lenBuf)
    var o = buff[ num ]
    //console.log( o.word + " " +o.translation + " " + o.id )
    buff.splice( num, 1 )

    var retValue = new Object()
    retValue.buf = buff
    retValue.obj = o

    return retValue
}

/*******************************************************************/

function wordTrue( word_id, value_count ) {
    /*var value_count = 0
    db.transaction( function(tx) {
                       var sql = "SELECT show_true FROM words WHERE id = ?"
                       var res = tx.executeSql( sql, [word_id] )
                       value_count = res.rows.item(i).show_true
                       console.log("value_count="+value_count)
                       value_count += 1
                   }
            )*/
    var retValue = false
    db.transaction( function(tx) {
                       var sql = "UPDATE words SET show_true = ? WHERE id = ?"
                       //console.log( "UPDATE words SET show_true = "+value_count+" WHERE id = "+word_id )
                       var res = tx.executeSql( sql, [value_count, word_id] )
                       if( res.rowsAffected == 1 ) {
                           retValue = true
                       }
                   }
            )
    return retValue
}

function wordFalse( word_id, value_count  ) {
    var retValue = false
    db.transaction( function(tx) {
                       var sql = "UPDATE words SET show_false = ? WHERE id = ?"
                       //console.log( "UPDATE words SET show_false = "+value_count+" WHERE id = "+word_id )
                       var res = tx.executeSql( sql, [value_count, word_id] )
                       if( res.rowsAffected == 1 ) {
                           retValue = true
                       }
                   }
            )
    return retValue
}

/*******************************************************************/
function strItemComment( text ) {
    var txt = text
    var r  = txt.split('\n');
    if( r[1] )
        txt = r[0] + "..."
    return txt
}


function strItem( objText, lenW ) {

    var lenStr = objText.text.length
    var w = objText.width
    var h = objText.height
    //console.log( "w="+w )
    //console.log( "h="+h )

    var lenT = lenStr * objText.font.pixelSize
    var numStr = Math.round( (lenT / w)*0.7 )
    if (numStr == 0)
        numStr = 1
    var hStrs = numStr * objText.font.pixelSize * 1.5

    //console.log( "lenT="+lenT )
    //console.log( "numStr="+numStr )
    //console.log( "hStrs="+hStrs )

    if( hStrs > h ) {
        var sizFont = objText.font.pixelSize
        for( var k=1; k <= 30; k++ ) {
            sizFont -= 1
            objText.font.pixelSize = sizFont
            lenT = lenStr * objText.font.pixelSize
            numStr = Math.round( (lenT / w)*0.7 )
            hStrs = numStr * objText.font.pixelSize * 1.5
            if( hStrs < h ) {
                break
            }
        }
    }

}

/*******************************************************************/

/* сохраняет слово в БД */
function addWord(word, translation, category_id) {
    var res = 0

    db.transaction( function(tx) {
                       var r = tx.executeSql( "INSERT INTO words (word, translation, show_true, show_false, category_id) VALUES (?, ?, ?, ?, ?)", [word, translation, 0, 0, category_id] )
                       if ( r.insertId > 0 ) {
                           res = r.insertId
                       }
                   }
                )
    return res
}

/* обновляет слово в БД */
function updateWord(id, word, translation, category_id) {
    var res = false

    db.transaction( function(tx) {
                       var r = tx.executeSql( "UPDATE words SET word = ?, translation = ?, category_id = ? WHERE id = ?", [word, translation, category_id, id] )
                       if ( r.rowsAffected == 1 ) {
                           res = true
                       }
                   }
                )
    return res
}

/* сохраняет категорию в БД */
function addCategory(name, descr) {
    var res = 0

    db.transaction( function(tx) {
                       var r = tx.executeSql( "INSERT INTO categories (category, description) VALUES (?, ?)", [name, descr] )
                       if ( r.insertId > 0 ) {
                           res = r.insertId
                       }
                   }
                )
    return res
}

function updateCategory(id, name, descr) {
    var res = false

    db.transaction( function(tx) {
                       var r = tx.executeSql( "UPDATE categories SET category=?, description=? WHERE id=?", [name, descr,id] )
                       if ( r.rowsAffected == 1 ) {
                           res = true
                       }
                   }
                )
    return res
}
/*******************************************************************/

/* возвращает общее число просмотров слов */
function getNumShow() {
    var ret = 0
    db.transaction( function(tx) {
                       var res = tx.executeSql( "SELECT SUM(show_true +show_false) AS ss FROM words" )
                       ret = res.rows.item(0).ss
                   }
                )
    return ret
}

/* возвращает общее число слов в базе */
function getNumWords() {
    var ret = 0
    db.transaction( function(tx) {
                       var res = tx.executeSql( "SELECT COUNT(*) AS ss FROM words" )
                       ret = res.rows.item(0).ss
                   }
                )
    return ret
}


/* общее число слов в без ошибок */
function getNumWordsOnlyTrue() {
    var ret = 0
    db.transaction( function(tx) {
                       var res = tx.executeSql( "SELECT COUNT(*) AS st FROM words WHERE show_false=0  AND show_true != 0" )
                       ret = res.rows.item(0).st
                   }
                )
    return ret
}

/* общее число слов в без единого правильного ответа */
function getNumWordsOnlyFalse() {
    var ret = 0
    db.transaction( function(tx) {
                       var res = tx.executeSql( "SELECT COUNT(*) AS sf FROM words WHERE show_true=0 AND show_false != 0" )
                       ret = res.rows.item(0).sf
                   }
                )
    return ret
}


/* возвращает общее число верных ghjcvjnhjd */
function getNumShowTrue() {
    var ret = 0
    db.transaction( function(tx) {
                       var res = tx.executeSql( "SELECT SUM(show_true) AS ss FROM words" )
                       ret = res.rows.item(0).ss
                   }
                )
    return ret
}

/* возвращает общее число верных ghjcvjnhjd */
function getNumShowFalse() {
    var ret = 0
    db.transaction( function(tx) {
                       var res = tx.executeSql( "SELECT SUM(show_false) AS ss FROM words" )
                       ret = res.rows.item(0).ss
                   }
                )
    return ret
}

/* сброс всей статистики */
function clearAllStatistics() {
    var ret = false
    db.transaction( function(tx) {
                       var res = tx.executeSql( "UPDATE words SET show_false=0,  show_true=0" )
                       if ( res.rowsAffected > 0 ) {
                           ret = true
                       }
                   }
                )
    return ret
}


